/*
 *   Copyright (C) 2007 by Andrzej Oczkowicz
 *   andrew_lz@poczta.fm
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 *   KMediaCatalog :)
 *
 */

#include <QDir>
#include <QTextStream>

#include "../../dbg.h"
#include "modout.h"


output::~ output()
{
  _D << "";
}


output::output(int version, const QString & name, const QString & description)
:kOutputBasic(version, name, description)
{
  _D << "";
  base = "";
  catalog = QDir::home().path() + "/tmp/kmedia/";
  QDir d(catalog);
  d.mkdir(catalog);
}

int output::sync()
{
}

int output::setCatalogFileName(const QString & fileName)
{
  ///catalog = fileName;
}

kNode * output::rootNode()
{
    QFileInfo fi(catalog + base);
    kNode * n = new kNode;
    n->data = fi.filePath();
    n->name = base;
    n->isDir = true;
    return n;
}

kNode * output::createNode(QFileInfo * fi)
{
  if (base.isEmpty() )
    base = fi->path();
  cout << "\tCreateNode: " << fi->filePath().toStdString() << endl;
  kNode * n = new kNode;
  QDir d;
  n->name = fi->fileName();
  n->isDir = fi->isDir();
  d.mkpath( catalog + fi->filePath() );
  n->data = fi->filePath();
  if ( fi->isDir() ){
    QFile f( catalog + fi->filePath() + "/directory" );
    if ( f.open(QIODevice::WriteOnly) ){
      f.flush();
    }
  }
  return n;
}

int output::addNodeData(kNode * node, const kBasicFileInfo * info)
{

}

kNode * output::createNode(kNode * parent, const kBasicFileInfo * info)
{
  cout << "\tCreateNode2: " << info->name.toStdString() << endl;
}

void output::freeNode(kNode * node)
{
  if (node){
    delete node;
  }
}

kNodes * output::subNodes(kNode * node)
{
  if (!node)
    return 0;
  QString dir( node->data );
  QDir dr(dir);
  dr.setFilter( QDir::Dirs | QDir::Hidden );
  QFileInfoList list( dr.entryInfoList() );
  QFileInfo *fi;
  kNodes * nd = new kNodes;
  for (int i=0; i < list.size(); i++ ){
    fi = &list[i];
    if ( fi->fileName() == "."  || fi->fileName() == ".." )
      continue;
    kNode * n = new kNode;
    n->data = fi->filePath();
    n->name = fi->fileName();
    n->isDir = QFileInfo(QString(n->data + "/directory")).exists();
    nd->append(n);
  }
  return nd;
}

void output::freeNodes(kNodes * nodes)
{
  if (nodes){
    for(int i=0; i<nodes->size(); i++)
      freeNode( nodes->at(i) );
    delete nodes;
  }
}




